<?php
namespace App\Socket\Controller\WebSocket;
use App\Socket\Logic\UserLogic;
use App\Socket\Logic\DeckCards;

class User extends Base
{
    /** 登录 */
    public function login()
    {
        $param = $this->request()->getArgs();                                               
        
        $userLogic = new UserLogic();

        $userLogic->login($this->client(),$param);                                  
    }

    /** 注册用户 */
    public function reg(){
        $param = $this->request()->getArgs();
        UserLogic::reg($this->client(),$param["username"],$param["password"]);
    }

    //连接房间
    public function joinRoom()
    {
        $param = $this->request()->getArgs();     
        $roomId = $param["roomId"];
        UserLogic::joinRoom($this->client(), $roomId);                        
    }

    /** 发牌 */
    public function SendCards(){
        $fd = $this->client()->getFd();
        
        

        //直接发牌
        $deck = new DeckCards();
        $deck->create();
        $cards = $deck->getCards(17);

        
        $msg = [
            "cmd"=>"Licensing",
            "data"=>[
                "cards"=>$cards,
                "target"=>UserLogic::getUser($fd),
            ]
        ];

        $this->send($msg,[$fd]);
    }

    /**
     * 退出房间
     * @return void
     */
    public function exitRoom()
    {
        $fd = $this->client()->getFd();
        UserLogic::exitRoom($fd);
    }


    private function send($obj, $fds=[])
    {
        $str = json_encode($obj);
        TaskManager::async((function () use ($str,$fds) {
            foreach ($fds as $fd) {
                ServerManager::getInstance()->getServer()->push($fd, $str);
            }
        }));
    }
}


// try{
//     $info = Db::name("user")->where("username",$username)->find();
    
// }catch(\Exception $e){
//     print_r($e->getMessage());
// }
